/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月19日
 */
package com.massyframework.beanskin.scriptengine.beancontext;

import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.script.ScriptEngine;

import com.massyframework.beanskin.ModuleListener;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.assembly.AssemblyConfig;
import com.massyframework.beanskin.assembly.AssemblyContext;
import com.massyframework.beanskin.assembly.AssemblyContextAware;
import com.massyframework.beanskin.assembly.beans.BeanNotFoundException;
import com.massyframework.beanskin.assembly.handling.DependencyServiceProvider;
import com.massyframework.beanskin.assembly.handling.HandlerBase;
import com.massyframework.beanskin.service.DependencyServiceDescriptor;
import com.massyframework.beanskin.service.ServiceRepository;
import com.massyframework.beanskin.service.script.ScriptEngineBuilder;
import com.massyframework.beanskin.service.script.ScriptEngineFactory;
import com.massyframework.beanskin.service.script.ScriptFile;
import com.massyframework.beanskin.util.classloading.ModuleClassLoader;

/**
 * 基于ScriptEngine的装配件上下文
 * @author huangkh
 */
public class ScriptEngineAssemblyContext extends HandlerBase implements AssemblyContext {
	
	private ScriptEngineContextAdapter beanContext;
	private volatile Map<String, Object> dependenciesMap;

	/**
	 * 构造方法
	 * 
	 * @param lifecycleManager {@link LifecylceManager}
	 * @param beanContext      {@link ScriptEngineContextAdapter}
	 */
	public ScriptEngineAssemblyContext() {
	}
	
	@Override
	public synchronized void init() throws Exception{
		if (this.beanContext == null) {
			this.dependenciesMap = new HashMap<>();
					
			Assembly assembly = this.getAssociatedAssembly();
			AssemblyConfig config = this.getAssemblyConfig();
			ServiceRepository repo = ServiceRepository.retrieveFrom(assembly);
			
			ScriptEngineFactory factory = this.getScriptEngineFactory(repo);
			//创建脚本
			ScriptEngine engine = factory.createScriptEngine(builder->{
				this.injectScriptObjects(builder, assembly, config, repo);
				this.loadScriptFiles(builder, assembly, config, repo);
				this.customizeConfigurer(builder);
			});
			
			this.beanContext = new ScriptEngineContextAdapter(engine);
			//后置处理
	        this.postProcessing(assembly);
		}
	}
		
	@Override
	public synchronized void destroy() {
		if (this.beanContext != null) {
			Assembly assembly = this.getAssociatedAssembly();
			this.beforeProcessing(assembly);
			this.beanContext = null;
		}
	}

	@Override
	public boolean containsBean(String beanName) {
		return this.beanContext.containsBean(beanName);
	}

	@Override
	public Object getBean(String beanName) throws BeanNotFoundException {
		return this.beanContext.getBean(beanName);
	}

	@Override
	public Class<?> getBeanType(String beanName) throws BeanNotFoundException {
		return this.beanContext.getBeanType(beanName);
	}

	@Override
	public <B> Map<String, B> getBeansOfType(Class<B> beanType) {
		return this.beanContext.getBeansOfType(beanType);
	}

	@Override
	public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annoType) {
		return this.beanContext.getBeansWithAnnotation(annoType);
	}

	@Override
	public List<String> getBeanNames() {
		return this.beanContext.getBeanNames();
	}
			
	/**
	 * 装配件配置项
	 * @return {@link AssemblyConfig}
	 */
	protected AssemblyConfig getAssemblyConfig() {
		return this.getAssociatedAssembly().getConfig();
	}
	
	/**
	 * 创建脚本引擎工厂
	 * @param repo {@link ServiceRepository}, 服务资源库
	 * @return {@link ScriptEngineFactory}
	 */
	protected ScriptEngineFactory getScriptEngineFactory(ServiceRepository repo) {
		ScriptEngineFactory result = repo.findService(ScriptEngineFactory.class).orElse(null);
		if (result == null) {
			result = new SimpleScriptEngineFactory(this.getAssociatedAssembly());
		}
		return result;
	}
	
	/**
	 * 注入脚本对象
	 * @param builder {@lfink ScriptEngineBuilder},脚本引擎构建器
	 * @param assembly {@link Assembly},装配件
	 * @param config {@link AssemblyConfig},配置项
	 * @param repo {@link ServiceRepository},服务资源库
	 */
	protected void injectScriptObjects(ScriptEngineBuilder builder, Assembly assembly, 
			AssemblyConfig config, ServiceRepository repo) {
		//注入知名服务
		builder.addObject("assembly",assembly);
		builder.addObject("assmeblyConfig",config);
		builder.addObject("serviceRepository",repo);
		
		this.dependenciesMap.put("assembly", assembly);
        this.dependenciesMap.put("assemblyConfig", assembly.getConfig());
        this.dependenciesMap.put("serviceRepository", repo);
		
        Map<DependencyServiceDescriptor<?>, Object> serviceMap = this.getDependencyServices();
        if (serviceMap != null) {
            for (Map.Entry<DependencyServiceDescriptor<?>, Object> entry : serviceMap.entrySet()) {
            	DependencyServiceDescriptor<?> descriptor = entry.getKey();
                Object service = entry.getValue();

                //注入依赖服务
                builder.addObject(descriptor.getBeanName(), service);
                this.dependenciesMap.put(descriptor.getBeanName(), service);
            }
        }
	}
	
	/**
	 * 加载脚本文件
	 * @param builder {@link ScriptEngineBuilder}
	 * @param assembly {@link Assembly},装配件
	 * @param config {@link AssemblyConfig},装配件配置项
	 * @param repo {@link ServiceRepository}, 服务资源库
	 */
	protected void loadScriptFiles(ScriptEngineBuilder builder, Assembly assembly, 
			AssemblyConfig config, ServiceRepository repo) {
		ModuleClassLoader classLoader = assembly.getModuleClassLoader();		
		String defaultJs = "BEANSKIN-INF/js/main.js";
		Set<String> fileNames = classLoader.getDescryptScriptFileNames();
		if (!fileNames.isEmpty()) {
			for (String fileName: fileNames) {
				//加密文件，仅从classLoader加载
				URL url = classLoader.getResource(fileName);
				if (url != null) {
					builder.addScriptFile(new ScriptFile(url, assembly, true));
				}
			}
			
		}else {
			//加载缺省的js
			URL url = classLoader.getResource(defaultJs);
			if (url != null) {
				builder.addScriptFile(new ScriptFile(url, assembly, true));
			}
		}
	}
	
	/**
	 * 后置处理
	 */
	protected void postProcessing(Assembly assembly) {
		Map<String, ModuleListener> listenerMap =
				this.getBeansOfType(ModuleListener.class);
		for (Map.Entry<String, ModuleListener> entry: listenerMap.entrySet()) {
			if (this.dependenciesMap.containsKey(entry.getKey())) {
				continue;
			}
			
			assembly.addListener(entry.getValue());
		}
		
		Map<String, AssemblyContextAware> awareMap =
				this.getBeansOfType(AssemblyContextAware.class);
		for (Map.Entry<String, AssemblyContextAware> entry: awareMap.entrySet()) {
			if (this.dependenciesMap.containsKey(entry.getKey())) {
				continue;
			}
			
			entry.getValue().setAssemblyContext(this);
		}
	}
	
	protected void beforeProcessing(Assembly assembly) {
		Map<String, AssemblyContextAware> awareMap =
				this.getBeansOfType(AssemblyContextAware.class);
		for (Map.Entry<String, AssemblyContextAware> entry: awareMap.entrySet()) {
			if (this.dependenciesMap.containsKey(entry.getKey())) {
				continue;
			}
			
			entry.getValue().setAssemblyContext(null);
		}
		
		Map<String, ModuleListener> listenerMap =
				this.getBeansOfType(ModuleListener.class);
		for (Map.Entry<String, ModuleListener> entry: listenerMap.entrySet()) {
			if (this.dependenciesMap.containsKey(entry.getKey())) {
				continue;
			}
			
			assembly.removeListener(entry.getValue());
		}
	}
	
	/**
     * 获取依赖服务实例
     * @return {@link Map}, 可能返回null.
     */
    protected Map<DependencyServiceDescriptor<?>, Object> getDependencyServices(){
        DependencyServiceProvider handler =
                this.findHandler(DependencyServiceProvider.class);
        if (handler != null) {
            return handler.getDependencyServices();
        }
        return Collections.emptyMap();
    }
		
	/**
	 * 自定义配置脚本引擎构建器
	 * @param builder {@link ScriptEngineBuilder}
	 */
	protected void customizeConfigurer(ScriptEngineBuilder builder) {
		
	}
	
	/**
	 * 脚本引擎上下文适配器
	 * @return {@link ScriptEngineContextAdapter}
	 */
	public ScriptEngineContextAdapter getScriptEngineContextAdapter() {
		return this.beanContext;
	}
	
	@Override
	public String toString() {
		return "ScriptEngineAssemblyContext";
	}

}
